#!/bin/sh /etc/rc.common
# SPDX-License-Identifier: MIT

##########################################################################
#
# Copyright (C) 2018-2020 Tano Systems LLC. All rights reserved.
# Anton Kikin <a.kikin@tano-systems.com>
#
##########################################################################

START=19
STOP=01

NAME=mstpd

USE_PROCD=1

. "$IPKG_INSTROOT/lib/functions/mstpd.sh"

start_service() {
	local mstpd_loglevel

	# Migrate old configuration structure to new
	/usr/libexec/mstpctl-utils/mstpd-config-migrate.sh

	config_load "${NAME}"
	config_get_bool mstpd_enabled 'global' 'enabled' 0
	config_get mstpd_loglevel 'global' 'loglevel' 2

	[ "$mstpd_enabled" -eq 0 ] && return

	procd_open_instance
	procd_set_param command ${MSTPD_BIN}

	# Don't daemonize, procd will handle that for us
	procd_append_param command -d

	# Set log level
	procd_append_param command -v ${mstpd_loglevel}

	# Log to syslog
	procd_append_param command -s

	# Set auto respawn behavior
	procd_set_param respawn
	procd_close_instance

	mstpd_log_info "init: started"
}

stop_service() {
	mstpd_log_info "init: stopped"
}

service_running() {
	pgrep "mstpd" &> /dev/null
}

add_interface_trigger()
{
	procd_add_interface_trigger "interface.*" "$1" /etc/init.d/mstpd reload
	mstpd_log_debug "init: added trigger for $1 interface"
}

service_triggers() {
	procd_add_config_trigger "config.change" "${NAME}" /etc/init.d/mstpd reload
	mstpd_log_debug "init: added trigger for ${NAME} config"

	procd_add_config_trigger "config.change" "network" /etc/init.d/mstpd reload
	mstpd_log_debug "init: added trigger for network config"

	config_load "${NAME}"

	# Add triggers for all controlled bridges
	local bridge bridges
	config_get bridges 'global' 'bridge'

	for bridge in $bridges; do
		add_interface_trigger ${bridge}
	done
}

reload_service() {
	mstpd_log_info "init: reloading (bridge = '$@')..."
	running || return 1

	mstpd_sanity_checks
	mstpd_configure "$@"

	mstpd_log_info "init: reloaded"
}
